<script setup>
import { treeselect as menuTreeselect } from '@/api/system/menu'

import { GetMenuPermAPI } from '@/api/system/billconfig'
import { computed } from 'vue'

const props = defineProps({
  // 数据
  data: {
    type: Array,
    default: [],
  },
  // 回显
  modelValue: {
    type: String || Number,
    default: '',
  },
  // 是否禁用
  disabled: {
    type: Boolean,
    default: false,
  },
  config: {
    type: Object,
    default: {
      children: 'children',
      label: 'label',
      value: 'value',
    },
  },
})

const emit = defineEmits(['change'])

// 单据配置数据
const menuOptions = ref([])
const objChange = ref({})
const billConfig = ref()
let storageIds = ''
let ids = ''

// const selsect = arr => {
//   try {
//     arr.forEach(item => {
//       storageIds += `${item[props.config.value]},`
//       if (item[props.config.value] == props.modelValue) {
//         ids = storageIds
//       } else {
//         if (!item?.children && item[props.config.value] != props.modelValue) storageIds = ''

//         if (item?.children) selsect(item.children)
//       }
//     })
//   } catch {
//   } finally {
//   }

//   billConfig.value = ids
//     .slice(0, ids.length - 1)
//     .split(',')
//     .map(item => Number(item))
// }

let a = {}
const selsectObj = (arr, id) => {
  return new Promise((resolve, reject) => {
    arr.forEach((item) => {
      if (item[props.config.value] == id) {
        a = item
      } else {
        if (item?.children) {
          selsectObj(item.children, id)
        }
      }
    })
    resolve(a)
  })
}

const nodeClick = async (val) => {
  if (!Array.isArray(val)) return console.error('Error: 空值')
  const id = billConfig.value[billConfig.value.length - 1]
  const res = await selsectObj(props.data, id)
  emit('change', billConfig.value[billConfig.value.length])
  emit('update:modelValue', val.join(','))
  // emit('update:modelValue', billConfig.value[billConfig.value.length - 1])
  const Obj = {
    id: 0,
    ids: '',
    info: res,
  }
  Obj.id = billConfig.value[billConfig.value.length - 1]
  Obj.ids = billConfig.value.join(',')
  emit('objChange', Obj)
}

watch(
  () => props.modelValue,
  (val) => {
    if (Array.isArray(val)) {
      billConfig.value = val
      nodeClick(val)
    }
  },
  { deep: true, immediate: true }
)

const data = computed(() => {
  return props.data.filter(
    (item) =>
      item.children.length > 0 &&
      item.children.every((itemy) => itemy.children?.length > 0)
  )
})
</script>

<template>
  <div style="width: 100%">
    <el-cascader
      v-model="billConfig"
      :disabled="props.disabled"
      :options="data"
      :props="{
        label: props.config.label || 'label',
        value: props.config.value || 'value',
        children: props.config.children || 'children',
      }"
      @change="nodeClick"
    />
  </div>
</template>
